<?php

namespace app\common\model;

use think\Model;
use Qiniu\Auth as Auth;
//use Qiniu\Config;
use Qiniu\Storage\BucketManager;
use Qiniu\Storage\UploadManager;
use Qiniu\Processing\PersistentFop;

require_once APP_PATH . '/../vendor/qiniu/autoload.php';

class Qiniu extends Model
{
    public function remove($path)
    {
        /*  $accessKey = getenv('QINIU_ACCESS_KEY');
         $secretKey = getenv('QINIU_SECRET_KEY');
         $bucket = getenv('QINIU_TEST_BUCKET'); */
        $accessKey = config('qiniu_access');
        $secretKey = config('qiniu_secret');
        $bucket = config('qiniu_bucket');
        $domain = config('qiniu_domain');
        $auth = new Auth($accessKey, $secretKey);
        $auth = new Auth($accessKey, $secretKey);
        $config = new \Qiniu\Config();
        $bucketManager = new \Qiniu\Storage\BucketManager($auth, $config);
        $err = $bucketManager->delete($bucket, $path);
    }

    public function upload($name = false, $ext = false)
    {
        $file = request()->file('file');
        // 要上传图片的本地路径
        $filePath = $file->getRealPath();
        if (!$ext) {
            $ext = pathinfo($file->getInfo('name'), PATHINFO_EXTENSION);  //后缀
        }
        if (!$ext) {
            $ext = 'png';
        }
        $allow = [
            'png', 'jpg', 'jpeg', 'gif', 'mp3', 'mp4', 'wav', 'mov', '3gp', '4gp', 'avi', 'rmvb', 'flv', 'm4a'
        ];
        if (!in_array($ext, $allow)) {
            return false;
        }
        // 上传到七牛后保存的文件名
        if ($name) {
            $key = str_replace('.', '', $_SERVER['SERVER_NAME']) . "/{$name}/" . date('Ymd') . "/" . date('His') . rand(0, 9999) . '.' . $ext;
        } else {
            $key = str_replace('.', '', $_SERVER['SERVER_NAME']) . "/" . date('Ymd') . "/" . date('His') . rand(0, 9999) . '.' . $ext;
        }
        $accessKey = config('qiniu_access');
        $secretKey = config('qiniu_secret');
        $auth = new Auth($accessKey, $secretKey);
        $bucket = config('qiniu_bucket');
        $domain = config('qiniu_domain');
        $token = $auth->uploadToken($bucket);
        $uploadMgr = new UploadManager();
        list($ret, $err) = $uploadMgr->putFile($token, $key, $filePath);
        if ($err !== null) {
            return false;
        } else {
            return $ret;
        }
    }

    public function upload_keep($name = false, $ext = false)
    {
        $file = request()->file('file');

        if (!$ext) {
            $ext = pathinfo($file->getInfo('name'), PATHINFO_EXTENSION);  //后缀
        }
        if (!$ext) {
            $ext = 'png';
        }
        if ($file) {
            $info = $file->move(ROOT_PATH . DS . 'public' . DS . 'upload' . DS . 'keep');
            $fileOldPath = ROOT_PATH . DS . 'public' . DS . 'upload' . DS . 'keep' . DS . $info->getSaveName();
            $filePath = ROOT_PATH . DS . 'public' . DS . 'upload' . DS . 'keep' . DS . time() . '.' . $ext;
            $this->compressed_image($fileOldPath, $filePath);
        }
        // 要上传图片的本地路径
        if (!isset($filePath)) {
            $filePath = $file->getRealPath();
        }

        if (!$ext) {
            $ext = pathinfo($file->getInfo('name'), PATHINFO_EXTENSION);  //后缀
        }
        if (!$ext) {
            $ext = 'png';
        }
        $allow = [
            'png', 'jpg', 'jpeg', 'gif', 'mp3', 'mp4', 'wav', 'mov', '3gp', '4gp', 'avi', 'rmvb', 'flv', 'm4a'
        ];
        if (!in_array($ext, $allow)) {
            return false;
        }
        // 上传到七牛后保存的文件名
        if ($name) {
            $key = str_replace('.', '', $_SERVER['SERVER_NAME']) . "/{$name}/" . date('Ymd') . "/" . date('His') . rand(0, 9999) . '.' . $ext;
        } else {
            $key = str_replace('.', '', $_SERVER['SERVER_NAME']) . "/" . date('Ymd') . "/" . date('His') . rand(0, 9999) . '.' . $ext;
        }
        $accessKey = config('qiniu_access');
        $secretKey = config('qiniu_secret');
        $auth = new Auth($accessKey, $secretKey);
        $bucket = config('qiniu_bucket');
        $domain = config('qiniu_domain');
        $token = $auth->uploadToken($bucket);
        $uploadMgr = new UploadManager();
        list($ret, $err) = $uploadMgr->putFile($token, $key, $filePath);
        if ($err !== null) {
            return false;
        } else {
            if ($filePath)
                unlink($filePath);
            if ($fileOldPath)
                unlink($fileOldPath);
            return $ret;
        }
    }

    /**
     * desription 压缩图片
     * @param sting $imgsrc 图片路径
     * @param string $imgdst 压缩后保存路径
     */
    public function compressed_image($imgsrc, $imgdst)
    {
        list($width, $height, $type) = getimagesize($imgsrc);
        $new_width = $width > 750 ? 750 : $width;
        $new_height = $height * ($new_width / $width);
        switch ($type) {
            case 1:
                $giftype = check_gifcartoon($imgsrc);
                if ($giftype) {
                    header('Content-Type:image/gif');
                    $image_wp = imagecreatetruecolor($new_width, $new_height);
                    $image = imagecreatefromgif($imgsrc);
                    imagecopyresampled($image_wp, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
                    //75代表的是质量、压缩图片容量大小
                    imagejpeg($image_wp, $imgdst, 75);
                    imagedestroy($image_wp);
                }
                break;
            case 2:
                header('Content-Type:image/jpeg');
                $image_wp = imagecreatetruecolor($new_width, $new_height);
                $image = imagecreatefromjpeg($imgsrc);
                imagecopyresampled($image_wp, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
                //75代表的是质量、压缩图片容量大小
                imagejpeg($image_wp, $imgdst, 75);
                imagedestroy($image_wp);
                break;
            case 3:
                header('Content-Type:image/png');
                $image_wp = imagecreatetruecolor($new_width, $new_height);
                $image = imagecreatefrompng($imgsrc);
                imagecopyresampled($image_wp, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
                //75代表的是质量、压缩图片容量大小
                imagejpeg($image_wp, $imgdst, 75);
                imagedestroy($image_wp);
                break;
        }
    }


    /* 本地图片上传到远程服务器 */
    public function local2remote($local, $name = false, $delete = true)
    {
        if (!file_exists($local)) {
            return false;
        }
        $filePath = $local;
        $ext = pathinfo($local, PATHINFO_EXTENSION);  //后缀
        // 上传到七牛后保存的文件名
        if ($name) {
            $key = str_replace('.', '', $_SERVER['SERVER_NAME']) . "/{$name}/" . date('Ymd') . "/" . date('His') . rand(0, 9999) . '.' . $ext;
        } else {
            $key = str_replace('.', '', $_SERVER['SERVER_NAME']) . "/" . date('Ymd') . "/" . date('His') . rand(0, 9999) . '.' . $ext;
        }
        $accessKey = config('qiniu_access');
        $secretKey = config('qiniu_secret');
        $auth = new Auth($accessKey, $secretKey);
        $bucket = config('qiniu_bucket');
        $domain = config('qiniu_domain');
        $token = $auth->uploadToken($bucket);
        $uploadMgr = new UploadManager();
        list($ret, $err) = $uploadMgr->putFile($token, $key, $filePath);
        if ($delete) {
            unlink($local);
        }
        if ($err !== null) {
            return false;
        } else {
            return $ret;
        }
    }

    /* amr转换为mp3 */
    public function amr2mp3($key, $name)
    {
        $accessKey = config('qiniu_access');
        $secretKey = config('qiniu_secret');
        $auth = new Auth($accessKey, $secretKey);
        $bucket = config('qiniu_bucket');
        $domain = config('qiniu_domain');
        $token = $auth->uploadToken($bucket);
        $pipeline = 'amr2mp3';
        $force = false;
        //转码完成后通知到你的业务服务器。
        //$notifyUrl = request()->domain().'/amr';
        $notifyUrl = 'http://shop.xixi05.cn/api/notify/amr/mall_id/1';

        $config = new \Qiniu\Config();
        //$config->useHTTPS=true;
        $pfop = new PersistentFop($auth, $config);
        //要进行转码的转码操作。 http://developer.qiniu.com/docs/v6/api/reference/fop/av/avthumb.html
        $fops = "avthumb/mp3|saveas/" . \Qiniu\base64_urlSafeEncode($bucket . ":" . $name);
        list($id, $err) = $pfop->execute($bucket, $key, $fops, $pipeline, $notifyUrl, $force);
        //echo "\n====> pfop avthumb result: \n";
        if ($err != null) {
            //var_dump($err);
        } else {
            //echo "PersistentFop Id: $id\n";
        }
        //查询转码的进度和状态
        list($ret, $err) = $pfop->status($id);
        // echo "\n====> pfop avthumb status: \n";
        if ($err != null) {
            // var_dump($err);
        } else {
            // var_dump($ret);
        }
    }

    /* 水印 */
    public static function buildWaterMark($url, $arr, $uid)
    {
        $userInfo = User::getOneById($uid);
        $url = tomedia($url);
        $url .= '?watermark/3';
        foreach ($arr['list'] as $v) {
            if ($v['type'] == 'nickname') {
                $v['type'] = 'text';
                $v['content'] = $userInfo['nickname'];
            } elseif ($v['type'] == 'head') {
                $v['type'] = 'img';
                $v['content'] = $userInfo['headimgurl'];
            } elseif ($v['type'] == 'qrcode') {
                $v['type'] = 'img';
                $href = request()->domain() . '/m/chat/pages/index/index?refer_id=' . $uid . '&mall_id=' . $userInfo['mall_id'];
                $href = str_replace('&', '%26', $href);
                $v['content'] = 'http://shop.xixi05.cn/qrcode?text=' . $href;
            }
            if ($v['type'] == 'text') {
                $v['fontSize'] *= 20;
                $url .= '/text/' . self::qiniubase64url($v['content']);
                $url .= "/gravity/NorthWest";
                $url .= "/dy/{$v['top']}";
                $url .= "/dx/{$v['left']}";
                $url .= "/fontsize/{$v['fontSize']}";
                $url .= "/fill/" . self::qiniubase64url($v['color']);
            } else {
                $width = $v['width'] * $v['scale'];
                $ws = $width / $arr['width'];
                $url .= '/image/' . self::qiniubase64url(tomedia($v['content']));
                $url .= "/gravity/NorthWest";
                $url .= "/dy/{$v['top']}";
                $url .= "/dx/{$v['left']}";
                $url .= "/ws/{$ws}";
            }
        }
        return $url;
    }

    public static function qiniubase64url($str)
    {
        return strtr(base64_encode($str), '+/', '-_');
    }

    /* 下载图片到本地 */
    public static function downloadFile($url, $ext = false)
    {
        $path = ROOT_PATH . "public" . DS . "cache" . DS;
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
        $file = curl_exec($ch);
        curl_close($ch);
        if (!$ext) {
            $ext = pathinfo($url, PATHINFO_BASENAME);
        }
        $filename = time() . uniqid() . $ext;
        $resource = fopen($path . $filename, 'a');
        fwrite($resource, $file);
        fclose($resource);
        return $path . $filename;
    }
}